package com.zyx.service.impl.busi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zyx.resource.DynProperties;
import com.zyx.service.AbstractMsgService;
import com.zyx.service.RequestMsgService;
import com.zyx.utils.DynamicMsgUtils;
import com.zyx.constants.Constants;
import com.zyx.constants.ChannelMap;
import com.zyx.dto.*;
import com.zyx.vo.NettyHttpResponse;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zyx.constants.Constants.*;
import static com.zyx.constants.RetCode.*;

/**
 * 描述说明:add people lib member from business request
 *
 * @author DQing
 * @version 1.0
 * @className PeopleAddRequestMsgServiceImpl
 * @date 2020/4/2 11:44
 */
@Slf4j
@Service
public class PeopleAddRequestMsgServiceImpl extends AbstractMsgService implements RequestMsgService {

    @Autowired
    DynProperties dynProperties;

    @Override
    public String msgType() {
        return Constants.INNER_PEOPLE_ADD;
    }

    @Override
    public void parseMsg(ChannelHandlerContext ctx, String content) {
        Channel channel = ctx.channel();
        log.info(" 业务平台请求人员增加报文内容：{}",content);
        BusiPersonDto busiPersonDto = JSONObject.parseObject(content,new TypeReference<BusiPersonDto>(){});
        String rpid = busiPersonDto.getRpid();
        String deviceNo = busiPersonDto.getDeviceNo();
        Channel deviceChannel = ChannelMap.getDeviceChannelByName(deviceNo);
        String message = null;
        if(deviceChannel == null){
            message = resBusiMessage(RETCODE_1000,rpid);
        }else{
            String requestMessage = remotingRequest(busiPersonDto);
            NettyHttpResponse nettyHttpResponse = getRemotingResponse(deviceChannel,
                    requestMessage,DEVICE_PERSON_URI,HTTP_METHOD_POST);
            message = parseDeviceMsg(nettyHttpResponse,rpid);
        }
        DynamicMsgUtils.toBusiResponse(channel,message);
    }


    private String remotingRequest(BusiPersonDto busiPersonDto){
        PersonInfo personInfo = new PersonInfo();
        personInfo.setPersonId(busiPersonDto.getUserId());
        personInfo.setPersonName(busiPersonDto.getUserName());

        List<PersonInfo> personInfoList  = new ArrayList<>();
        personInfoList.add(personInfo);

        PersonInfoDto personInfoDto = new PersonInfoDto();
        personInfoDto.setPersonList(personInfoList);
        personInfoDto.setNum(Long.valueOf(personInfoList.size()));

        JSONObject json = (JSONObject) JSON.toJSON(personInfoDto);
        return json.toString();
    }



}
